package com.edushare.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.edushare.R;
import com.edushare.controller.GroupController;
import com.edushare.entity.Group;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class GroupActivity extends Activity {

	private GroupController gc = new GroupController();
	private ListView listview;
	private ArrayList<Group> groups = new ArrayList<Group>();
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
			.cacheOnDisc(true).build();
	final Context context = this;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_layout);
		
		// set image loader configuration
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(defaultOptions)
				.build();
		imageLoader.init(config);

		// retrieve group details
		groups = gc.retrieveGroups();

		if (groups != null) {
			listview =  (ListView) findViewById(R.id.groupList);
			ListAdapter listAdapter = new ListAdapter(GroupActivity.this);
			listview.setAdapter(listAdapter);
			listAdapter.notifyDataSetChanged();
		}

		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int temp,
					long arg3) {

				final int _groupID = groups.get(temp).getGroupID();
				final String _groupName = groups.get(temp).getName().trim();
				final String _groupdescription = groups.get(temp).getDescription()
						.trim();
				final String _groupimagepath = groups.get(temp).getImagePath().trim();
				final String _password = groups.get(temp).getPassword().trim();

				if (_password == null || _password.equals("")) {
					Intent intent = new Intent(GroupActivity.this,
							GroupMedias.class);

					Bundle bundle = new Bundle();
					bundle.putInt("groupid", _groupID);
					bundle.putString("groupname", _groupName);
					bundle.putString("groupdescription", _groupdescription);
					bundle.putString("groupimagepath", _groupimagepath);

					intent.putExtras(bundle);
					startActivity(intent);
				} else {
					// custom dialog
					final Dialog dialog = new Dialog(context);
					dialog.setContentView(R.layout.popup_password);
					dialog.setTitle("Please enter group password");
					final EditText password = (EditText) dialog.findViewById(R.id.passwordEt);
					Button dialogButton = (Button) dialog.findViewById(R.id.submitBtn);
					// if button is clicked, close the custom dialog
					dialogButton.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							String pwd = password.getText().toString();
							if(_password.equals(pwd)){
								Intent intent = new Intent(GroupActivity.this,
										GroupMedias.class);
	
								Bundle bundle = new Bundle();
								bundle.putInt("groupid", _groupID);
								bundle.putString("groupname", _groupName);
								bundle.putString("groupdescription", _groupdescription);
								bundle.putString("groupimagepath", _groupimagepath);
	
								intent.putExtras(bundle);
								startActivity(intent);
							}
							dialog.dismiss();
						}
					});
		 
					dialog.show();
					
				}
			}
		});

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.group, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle presses on the action bar items
		switch (item.getItemId()) {
		case R.id.mAddGroup:
			openGroupCreate();
			return true;
		case R.id.mAboutUs:
			openAboutUs();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void openGroupCreate() {
		Intent intent = new Intent(GroupActivity.this,
				GroupCreateActivity.class);
		startActivity(intent);
	}

	private void openAboutUs() {
		Intent intent = new Intent(GroupActivity.this, AboutUsActivity.class);
		startActivity(intent);
	}

	private class ListAdapter extends BaseAdapter {

		LayoutInflater inflater;
		ViewHolder viewHolder;

		public ListAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return groups.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return groups.get(position).getGroupID();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			parent.invalidate();
			convertView = inflater.inflate(R.layout.group_list_row, null);
			viewHolder = new ViewHolder();

			viewHolder.groupNameTV = (TextView) convertView
					.findViewById(R.id.groupNameTV);
			viewHolder.descriptionTV = (TextView) convertView
					.findViewById(R.id.descriptionTV);
			viewHolder.groupIconIV = (ImageView) convertView
					.findViewById(R.id.groupIconIV);
			viewHolder.progBar = (ProgressBar) convertView
					.findViewById(R.id.progBar);

			convertView.setTag(viewHolder);

			viewHolder.groupNameTV.setText(groups.get(position).getName());
			viewHolder.descriptionTV.setText(groups.get(position)
					.getDescription());

			// Load bitmap from internet or from memory
			URL onLineURL;
			try {
				onLineURL = new URL(groups.get(position).getImagePath());
				imageLoader.displayImage(onLineURL.toString(), viewHolder.groupIconIV);
				viewHolder.groupIconIV.setVisibility(View.VISIBLE);
				viewHolder.progBar.setVisibility(View.GONE);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

			/*
			 * (convertView.findViewById(R.id.groupRow)) .setOnClickListener(new
			 * OnClickListener() {
			 * 
			 * @Override public void onClick(View arg0) {
			 * 
			 * String _groupName = _groupList.get(temp) .getName().trim();
			 * String _groupdescription = _groupList.get(temp)
			 * .getDescription().trim(); String _groupimagepath =
			 * _groupList.get(temp) .getImagePath().trim();
			 * 
			 * Intent intent = new Intent(getActivity(), GroupDetail.class);
			 * 
			 * Bundle bundle = new Bundle(); bundle.putString("groupName",
			 * _groupName); bundle.putString("groupdescription",
			 * _groupdescription); bundle.putString("groupimagepath",
			 * _groupimagepath); intent.putExtras(bundle);
			 * startActivity(intent);
			 * 
			 * } });
			 */
			return convertView;

		}
	}

	

	private class ViewHolder {
		public TextView groupNameTV;
		public ImageView groupIconIV;
		public TextView descriptionTV;
		public ProgressBar progBar;
	}

}
